package com.etone.smartAudit.utils;

/**
 * @author by Quyj
 * @description AES加解密工具
 * @date 2019/8/1
 */

import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class AESUtils {


    /**
     * 为了配合c 那边补充 zeropadding  修改aes ecb nopadding 然后做补零处理加密
     */
    public static String encryptWithFunc(String data, String key){
        if(StringUtils.isBlank(key)){
            return null;
        }
        key = key.substring(0,16);
        String result = encrypt(data,key);
        return result;
    }
    //加密
    public static String encrypt(String data, String key) {


        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
            int blockSize = cipher.getBlockSize();
            byte[] dataBytes = data.getBytes();
            int length = dataBytes.length;
            //计算需填充长度
            if (length % blockSize != 0) {
                length = length + (blockSize - (length % blockSize));
            }
            byte[] plaintext = new byte[length];
            //填充
            System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
            //设置偏移量参数
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
            byte[] encryped = cipher.doFinal(plaintext);

            return parseByte2HexStr(encryped);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }
    public static String parseByte2HexStr(byte[] buf) {
        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < buf.length; ++i) {
            String hex = Integer.toHexString(buf[i] & 255);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }

        return sb.toString();
    }
    //解密
    public static String desEncrypt(String data, String key) {


        try {
            byte[] encryp = parseHexStr2Byte(data);
            Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            byte[] original = cipher.doFinal(encryp);
            return new String(original,"UTF-8").trim();
        } catch (Exception e) {
            // TODO: handle exception
        }
        return null;
    }

    public static String desEncryptWithFunc(String data, String sid) {
        if (sid == null) return null;
        String key = sid.substring(0,16);
        try {
            byte[] encryp = parseHexStr2Byte(data);
            Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            byte[] original = cipher.doFinal(encryp);
            return new String(original,"UTF-8").trim();
        } catch (Exception e) {
            // TODO: handle exception
        }
        return null;
    }

    /**
     * AES解密操作
     *
     * @param encryptContent 加密的密文
     * @param password       解密的密钥
     * @return
     */
    public static String decrypt(String encryptContent, String password) {
        if (StringUtils.isBlank(password)) {
            return null;
        }
        Cipher cipher = null;
        try {
            byte[] encryp = parseHexStr2Byte(encryptContent);
            cipher = Cipher.getInstance("AES/ECB/NoPadding");
            //设置为解密模式
            SecretKeySpec keySpec = new SecretKeySpec(password.getBytes(), "AES");
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            //执行解密操作
            byte[] result = cipher.doFinal(encryp);
            return new String(result, "UTF-8").trim();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static SecretKeySpec getSecretKey(final String password) throws NoSuchAlgorithmException {
        //生成指定算法密钥的生成器
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128, new SecureRandom(password.getBytes()));
        //生成密钥
        SecretKey secretKey = keyGenerator.generateKey();
        //转换成AES的密钥
        return new SecretKeySpec(secretKey.getEncoded(), "AES");
    }

    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        } else {
            byte[] result = new byte[hexStr.length() / 2];

            for (int i = 0; i < hexStr.length() / 2; ++i) {
                int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
                int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
                result[i] = (byte) (high * 16 + low);
            }
            return result;
        }
    }

    public static void main(String[] args) {
        String desUserInfo = AESUtils.desEncrypt("0280A7C2E42F17D7516B1A94EA9C9744383BEE89A78806DA43EFC07F2FAA7E90CC835E9347CDDCE503D526390368DB42C890607AE4D25403A261C94A466645B9","bRLGAwD1IkzuZ5G1");

        String mfZG5kMM86T4V6Nx = AESUtils.encrypt("phonenumber=19802021040&type=3&userTime=2021-02-0214:00:00", "bRLGAwD1IkzuZ5G1");

        System.out.println(desUserInfo);
    }


}